"""
Initial setup script for Meeting Room Booking System
Creates admin and demo users, and sample data
"""
import sys
from pathlib import Path

# Add parent directory to path
sys.path.append(str(Path(__file__).parent.parent))

from app.database import SessionLocal, engine, Base
from app.models.user import User, UserRole
from app.models.room import Room, RoomStatus
from app.models.schedule import Schedule
from app.models.system_config import SystemConfig
from app.utils.security import get_password_hash
from datetime import time
import uuid

def create_tables():
    """Create all database tables"""
    print("Creating database tables...")
    Base.metadata.create_all(bind=engine)
    print("✓ Tables created successfully")

def create_users(db):
    """Create admin and demo users"""
    print("\nCreating users...")
    
    # Check if users already exist
    existing_admin = db.query(User).filter(User.username == "admin").first()
    existing_demo = db.query(User).filter(User.username == "demo").first()
    
    if existing_admin and existing_demo:
        print("✓ Users already exist")
        return
    
    users_to_create = []
    
    if not existing_admin:
        admin = User(
            id=uuid.uuid4(),
            username="admin",
            email="admin@example.com",
            password_hash=get_password_hash("admin"),
            role=UserRole.ADMIN
        )
        users_to_create.append(admin)
    
    if not existing_demo:
        demo = User(
            id=uuid.uuid4(),
            username="demo",
            email="demo@example.com",
            password_hash=get_password_hash("demo"),
            role=UserRole.USER
        )
        users_to_create.append(demo)
    
    if users_to_create:
        db.add_all(users_to_create)
        db.commit()
        print(f"✓ Created {len(users_to_create)} user(s)")
    
    print("  - Admin: username='admin', password='admin'")
    print("  - Demo User: username='demo', password='demo'")

def create_sample_rooms(db):
    """Create sample meeting rooms"""
    print("\nCreating sample meeting rooms...")
    
    # Check if rooms already exist
    existing_rooms = db.query(Room).count()
    if existing_rooms > 0:
        print(f"✓ {existing_rooms} room(s) already exist")
        return
    
    rooms = [
        Room(
            id=uuid.uuid4(),
            name="Conference Room A",
            capacity=10,
            location="Building A, Floor 3",
            facilities=["Projector", "Whiteboard", "Video Conference"],
            status=RoomStatus.ACTIVE
        ),
        Room(
            id=uuid.uuid4(),
            name="Conference Room B",
            capacity=20,
            location="Building A, Floor 3",
            facilities=["Projector", "Whiteboard", "Audio System"],
            status=RoomStatus.ACTIVE
        ),
        Room(
            id=uuid.uuid4(),
            name="Meeting Room 301",
            capacity=6,
            location="Building B, Floor 3",
            facilities=["Whiteboard", "TV Screen"],
            status=RoomStatus.ACTIVE
        ),
        Room(
            id=uuid.uuid4(),
            name="Board Room",
            capacity=15,
            location="Building A, Floor 5",
            facilities=["Projector", "Video Conference", "Premium Chairs"],
            status=RoomStatus.ACTIVE
        ),
    ]
    
    db.add_all(rooms)
    db.commit()
    print(f"✓ Created {len(rooms)} meeting room(s)")
    
    return rooms

def create_system_configs(db):
    """创建系统配置（管理员密码等）"""
    print("\n创建系统配置...")
    
    # 检查管理员密码配置是否已存在
    existing_config = db.query(SystemConfig).filter(
        SystemConfig.config_key == "admin_password"
    ).first()
    
    if existing_config:
        print("✓ 系统配置已存在")
        return
    
    # 创建默认管理员密码配置
    admin_password_config = SystemConfig(
        id=uuid.uuid4(),
        config_key="admin_password",
        config_value=get_password_hash("123456789"),  # 默认密码：123456789
        description="管理员登录密码"
    )
    
    db.add(admin_password_config)
    db.commit()
    print("✓ 创建系统配置成功")
    print("  - 管理员密码: 123456789 (默认)")

def create_default_schedules(db, rooms):
    """Create default schedules for all rooms (Mon-Fri 8:00-18:00)"""
    print("\nCreating default schedules...")
    
    # Check if schedules already exist
    existing_schedules = db.query(Schedule).count()
    if existing_schedules > 0:
        print(f"✓ {existing_schedules} schedule(s) already exist")
        return
    
    schedules = []
    
    for room in rooms:
        # Monday to Friday (0-4)
        for day in range(5):
            schedule = Schedule(
                id=uuid.uuid4(),
                room_id=room.id,
                day_of_week=day,
                open_time=time(8, 0),
                close_time=time(18, 0),
                is_available=True
            )
            schedules.append(schedule)
        
        # Saturday and Sunday (5-6)
        for day in range(5, 7):
            schedule = Schedule(
                id=uuid.uuid4(),
                room_id=room.id,
                day_of_week=day,
                open_time=time(0, 0),
                close_time=time(0, 0),
                is_available=False
            )
            schedules.append(schedule)
    
    db.add_all(schedules)
    db.commit()
    print(f"✓ Created {len(schedules)} schedule(s)")

def main():
    """Main setup function"""
    print("=" * 60)
    print("Meeting Room Booking System - Initial Setup")
    print("=" * 60)
    
    try:
        # Create tables
        create_tables()
        
        # Create database session
        db = SessionLocal()
        
        try:
            # Create users
            create_users(db)
            
            # Create system configs
            create_system_configs(db)
            
            # Create sample rooms
            rooms = create_sample_rooms(db)
            
            # Create default schedules
            if rooms:
                create_default_schedules(db, rooms)
            
            print("\n" + "=" * 60)
            print("✓ Setup completed successfully!")
            print("=" * 60)
            print("\nYou can now:")
            print("1. Access the application at http://localhost")
            print("2. Login as admin (admin/admin) or demo user (demo/demo)")
            print("3. Start managing meeting rooms and bookings")
            print("\n" + "=" * 60)
            
        finally:
            db.close()
            
    except Exception as e:
        print(f"\n✗ Setup failed: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()
